package com.lvmama.task.job.worker;


import com.lvmama.task.common.service.TaskService;
import com.lvmama.task.common.vo.Task;
import com.lvmama.task.job.common.TaskJobParameters;
import com.lvmama.task.job.thread.TaskThread;
import com.lvmama.task.job.thread.TaskThreadPoolFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.<p/>
 * User: troy-kou<p/>
 * Date: 14-1-6<p/>
 * Time: 下午4:00<p/>
 * Email:kouhongyu@163.com<p/>
 */
@Service
public class TaskExecuteJob {

    Log log = LogFactory.getLog(TaskExecuteJob.class);
    private TaskService taskService;

    public void execute() {

        Map<String, Object> paramMap = new HashMap<String, Object>();

        paramMap.put("available", Task.TASK_AVAILABLE.ENABLE.getCode());//任务为“启用”
        paramMap.put("status", Task.TASK_STATUS.WAIT.getCode());//运行状态为“等待”
        paramMap.put("currentTime", new Date(System.currentTimeMillis()));
        paramMap.put("jobNode", TaskJobParameters.TASK_JOB_NODE);
        paramMap.put("owner", TaskJobParameters.TASK_JOB_OWNER);

        paramMap.put("_startRow", 1);
        paramMap.put("_endRow", 10000);

        List<Task> taskList = taskService.getTaskList(paramMap);

        for (Task task : taskList) {
            try {
                /**
                 * 如果Task 不是"运行"状态
                 */
                if (!TaskThreadPoolFactory.getInstance().isRunningTask(task.getTaskId())) {

                    TaskThread taskThread = new TaskThread();
                    taskThread.setTask(task);
                    taskThread.setTaskService(taskService);

                    TaskThreadPoolFactory.getInstance().addThread(taskThread);
                }
            } catch (Exception e) {
                log.error(e);
            }
        }
    }

    public TaskService getTaskService() {
        return taskService;
    }

    public void setTaskService(TaskService taskService) {
        this.taskService = taskService;
    }
}
